package com.toyota.toyotaownerspoc.main;

import android.util.Log;
import java.util.HashMap;
import java.util.List;
import com.toyota.toyotaownerspoc.R;
import com.toyota.toyotaownerspoc.explore.Explore;
import com.toyota.toyotaownerspoc.nearby.Nearby;
import com.toyota.toyotaownerspoc.options.Information;
import com.toyota.toyotaownerspoc.options.Settings;
import com.toyota.toyotaownerspoc.vehicle.Vehicle;
import com.toyota.toyotaownerspoc.service.Service;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.Toast;



/*
 List :
 Nearby
 Service
 Vehicle
 Explore

 HP04 Ability to View Settings: On tap of the menu icon (top
 left), the Settings Panel1 will be displayed

 HP05 Ability to View All Available Sections of the App: The
 homepage will contain options for all the following sections:
 Nearby
 Service
 Vehicle
 Explore
 HP06 Ability to Navigate to the Nearby Section: On tap of
 the Nearby option on the homepage, the user will be redirected
 to the Nearby section with the Dealer Listings page displayed by
 default.
 HP07 Ability to Navigate to the Service Section: On tap of
 the Service option on the homepage, the user will be redirected
 to the Service section with the Service History page displayed by
 default.
 HP08 Ability to Navigate to the Vehicle Section: On tap of
 the Vehicle option on the homepage, the user will be redirected
 to the Vehicle section with the Dashboard Icons page displayed
 by default.
 HP09 Ability to Navigate to the Explore Section: On tap of
 the Explore option on the homepage, the user will be redirected
 to the Explore section with options for the following:
 Events
 Toyota Care
 Safety Connect
 Entune
 */
public class ActivitytToyotaOwnersMainListView extends Activity {

	
	public ListView listView;
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		   setContentView(R.layout.activity_toyota_owners_main);
		
		ListViewItemModelLoader.LoadModel();
		
        listView = (ListView) findViewById(R.id.toyota_owners_main_list_view);
        
        if (listView!=null)
        {
        
        String[] ids = new String[ListViewItemModelLoader.Items.size()];
        for (int i= 0; i < ids.length; i++){

            ids[i] = Integer.toString(i+1);
        }

        ItemAdapter adapter = new ItemAdapter(this,R.layout.main_activity_view_icons, ids);
        listView.setAdapter(adapter);
       
        listView.requestLayout();
        }
        else
        {	Log.d("***Class ActivitytToyotaOwnersMainListView, listView: ",
				String.valueOf(listView));
        	
        }
        
       
		// OnItemClickListener
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
		
			@Override
			// onItemClick
			public void onItemClick(AdapterView<?> parent, final View view,
					int position, long id) {

				/*
				 * 0 - Nearby 1 - Service 2 - Vehicle 3 - Explore
				 */

				if (position == 0) {
					Intent i = new Intent(view.getContext(), Nearby.class);
					startActivity(i);
			} else if (position == 1) {
					Intent i = new Intent(view.getContext(), Service.class);
				startActivity(i);
				} else if (position == 2) {
					Intent i = new Intent(view.getContext(), Vehicle.class);
					startActivity(i);
				} else if (position == 3) {
					Intent i = new Intent(view.getContext(), Explore.class);
					startActivity(i);
				} else {
					// do nothing
				}

			}
		});
		
		
		ImageView HomeHeaderLeftImageView = (ImageView) findViewById(R.id.image_home_header_left);
		
		if (HomeHeaderLeftImageView!=null)
		{
		HomeHeaderLeftImageView.setOnClickListener(new View.OnClickListener() {

	
			  @Override
			  public void onClick(View view) {
				  Intent i = new Intent(view.getContext(), Settings.class);
					startActivity(i);
			  }

			});
		
		final Toast viewToast = Toast.makeText(this, "Click to see settings panel", Toast.LENGTH_SHORT);
		
		HomeHeaderLeftImageView.setOnHoverListener(  new View.OnHoverListener() {
			
			@Override
			public boolean onHover(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				
				viewToast.show();
				return false;
			}
		
		});		
		
		}
		else
		{
			Log.d("***ActivityToyotaOwnersMainListView class , HomeHeaderLeftImageView: ",String.valueOf(HomeHeaderLeftImageView));
		}
		
		
ImageView HomeHeaderRightImageView = (ImageView) findViewById(R.id.image_home_header_right);


if (HomeHeaderRightImageView!=null)
{
		HomeHeaderRightImageView.setOnClickListener(new View.OnClickListener() {

				  @Override
				  public void onClick(View view) {
					  Intent i = new Intent(view.getContext(), Information.class);
						startActivity(i);
				  }
			

			});
		
final Toast viewToast = Toast.makeText(this, "Click to see information panel", Toast.LENGTH_SHORT);
		
		HomeHeaderLeftImageView.setOnHoverListener(  new View.OnHoverListener() {
			
			@Override
			public boolean onHover(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				
				viewToast.show();
				return false;
			}
		
		});	
}
else
{
	Log.d("***ActivityToyotaOwnersMainListView class , HomeHeaderRightImageView: ",String.valueOf(HomeHeaderRightImageView));
}
		
	}
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		
		
		super.onResume();
		//call alert dialog methods 
		handleLocationPopupWindow(findViewById(R.id.toyota_owners_main_list_view));
		handleNotificationPopupWindow(findViewById(R.id.toyota_owners_main_list_view));
		//call GPS method 
		getGPSLocation(findViewById(R.id.toyota_owners_main_list_view));
	}
	

	
	public void getGPSLocation(View view)
	{
		//if location services are allowed 
		SharedPreferences preferences = getSharedPreferences(
				toyotaOwnersGlobal.PREFERENCES_FILE, MODE_PRIVATE);
		
		boolean locationServicesFlag = preferences.getBoolean(toyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES,false);
		
		if (locationServicesFlag)
		{
			//display current longitude & latitude , as Toast for testing 
			 GpsLocaton newGpsLocaton = new GpsLocaton(); 
			 //display GPS location for 2 seconds
			
			Toast.makeText(view.getContext(),"Longitude: "+newGpsLocaton.getLongitude()+" - Latitude: "+newGpsLocaton.getLatitude(),2).show();
		}
		else
		{
			Log.d("***onResume(): ", String.valueOf(locationServicesFlag));
		}
	}
	

	class StableArrayAdapter extends ArrayAdapter<String> {

		HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

		public StableArrayAdapter(Context context, int textViewResourceId,
				List<String> objects) {
			super(context, textViewResourceId, objects);
			for (int i = 0; i < objects.size(); ++i) {
				mIdMap.put(objects.get(i), i);
			}
		}

		@Override
		public long getItemId(int position) {
			String item = getItem(position);
			return mIdMap.get(item);
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

	}//end inner class StableArrayAdapter 
	
	/*
	 * Ability to Use the User's Current Location A pop-up window will be
	 * displayed to the user on load of the homepage asking if the user would
	 * like to allow the app access to their current location. If the users
	 * allow the app access to their current location, the app will store this
	 * information for the duration of the user's session.
	 * 
	 * The pop-up window will contain the following CTAs: Don't Allow OK
	 */

	public void handleLocationPopupWindow(final View view ) {
		Log.d("***ActivitytToyotaOwnersMainListView",
				"handleLocationPopupWindow()");
		/*
		 * 1) check if location preferences were set before if yes than do
		 * nothing, else display popup 2) set preferences 3) display main
		 * activity
		 */
		try {
			if (view!=null)
			{
			final SharedPreferences preferences = getSharedPreferences(
					toyotaOwnersGlobal.PREFERENCES_FILE, MODE_PRIVATE);
			// check to see if the location preferences was set before
			boolean locationPreferencesWereSetBefore = preferences
					.getAll()
					.containsKey(
							toyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES);

			if (locationPreferencesWereSetBefore) {
				Log.d("handleLocationPopupWindow(), locationPreferencesWereSetBefore: ",
						String.valueOf(locationPreferencesWereSetBefore));
				boolean ALLOWED_TO_USE_LOCATION_SERVICES = preferences
						.getBoolean(
								toyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES,
								false);
				if (ALLOWED_TO_USE_LOCATION_SERVICES) {
					// use location services, store GPS location
					//display current longitude & latitude , as Toast for testing 
					 GpsLocaton newGpsLocaton = new GpsLocaton(); 
					 //display GPS location for 2 seconds
					
					Toast.makeText(view.getContext(),"Longitude: "+newGpsLocaton.getLongitude()+" - Latitude: "+newGpsLocaton.getLatitude(),2).show();
				} else {
					// do nothing
				}
			}// end if locationPreferencesWereSetBefore were set
			else {
				Log.d("handleLocationPopupWindow(), locationPreferencesWereSetBefore: ",
						String.valueOf(locationPreferencesWereSetBefore));

				//instantiate alert dialog 
				AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
				//set alert message
				builder.setMessage(R.string.location_permission_popup_text);
				//add buttons & listeners 
				// Add the buttons
				builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				              //persist preferences 
				        	     SharedPreferences.Editor editor = preferences.edit();
				        	     //since user selects ok, than oyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES = true
								 editor.putBoolean(toyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES,true); 
								 //commit
								 editor.commit();
								 
							
				           }
				       });
				
				builder.setNegativeButton(R.string.dont_allow, new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				      
				        	   //persist preferences 
				        	     SharedPreferences.Editor editor = preferences.edit();
				        	     //since user selects dont allow , than oyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES = false
								 editor.putBoolean(toyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES,false); 
								 //commit
								 editor.commit();
								
				           }
				       });
				// Create the AlertDialog
				AlertDialog dialog = builder.create();
				dialog.show();
				
			}// end location settings were not set or found
		}//end if 
			else
			{
				Log.d("handleLocationPopupWindow() view is", "NULL");
			}
		}// end try
		catch (Exception exc) {
			String message = exc.getMessage();
			Log.d("handleLocationPopupWindow()", message);
			exc.printStackTrace();
		}
	}// end handle location popup
	/*
	 * Ability to Notify Users of Notifications: A pop-up window will be
	 * displayed to the user on load of the homepage asking if the user would
	 * like to allow the app to send them notifications. The pop-up window will
	 * contain the following CTAs: Don't Allow OK
	 */

	public void handleNotificationPopupWindow(final View view ) {
		Log.d("***ActivitytToyotaOwnersMainListView",
				"handleNotificationPopupWindow()");
		/*
		 * 1) check if location preferences were set before if yes than do
		 * nothing, else display popup 2) set preferences 3) display main
		 * activity
		 */
		try {
			if (view!=null)
			{
			final SharedPreferences preferences = getSharedPreferences(
					toyotaOwnersGlobal.PREFERENCES_FILE, MODE_PRIVATE);
			// check to see if the location preferences was set before
			boolean locationPreferencesWereSetBefore = preferences
					.getAll()
					.containsKey(
							toyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES);

			if (locationPreferencesWereSetBefore) {
				Log.d("handleNotificationPopupWindow(), locationPreferencesWereSetBefore: ",
						String.valueOf(locationPreferencesWereSetBefore));
				boolean ALLOWED_TO_USE_NOTIICATION_SERVICES = preferences
						.getBoolean(
								toyotaOwnersGlobal.ALLOWED_TO_USE_NOTIFICATION_SERVICES,
								false);
				if (ALLOWED_TO_USE_NOTIICATION_SERVICES) {
					// use location services, store GPS location
					//display current longitude & latitude , as Toast for testing 
					 GpsLocaton newGpsLocaton = new GpsLocaton(); 
					 //display GPS location for 2 seconds
					
					Toast.makeText(view.getContext(),"Longitude: "+newGpsLocaton.getLongitude()+" - Latitude: "+newGpsLocaton.getLatitude(),2).show();
				} else {
					// do nothing
				}
			}// end if locationPreferencesWereSetBefore were set
			else {
				Log.d("handleNotificationPopupWindow(), locationPreferencesWereSetBefore: ",
						String.valueOf(locationPreferencesWereSetBefore));

				//instantiate alert dialog 
				AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
				//set alert message
				builder.setMessage(R.string.notification_permission_popup_text);
				//add buttons & listeners 
				// Add the buttons
				builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				              //persist preferences 
				        	     SharedPreferences.Editor editor = preferences.edit();
				        	     //since user selects ok, than oyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES = true
								 editor.putBoolean(toyotaOwnersGlobal.ALLOWED_TO_USE_NOTIFICATION_SERVICES,true); 
								 //commit
								 editor.commit();
				           }
				       });
				
				builder.setNegativeButton(R.string.dont_allow, new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				      
				        	   //persist preferences 
				        	     SharedPreferences.Editor editor = preferences.edit();
				        	     //since user selects dont allow , than oyotaOwnersGlobal.ALLOWED_TO_USE_LOCATION_SERVICES = false
								 editor.putBoolean(toyotaOwnersGlobal.ALLOWED_TO_USE_NOTIFICATION_SERVICES,false); 
								 //commit
								 editor.commit();
								
				           }
				       });
				// Create the AlertDialog
				AlertDialog dialog = builder.create();
				dialog.show();
				
			}// end location settings were not set or found
		}//end if 
			else
			{
				Log.d("handleNotificationPopupWindow() view is", "NULL");
			}
		}// end try
		catch (Exception exc) {
			String message = exc.getMessage();
			Log.d("handleNotificationPopupWindow()", message);
			exc.printStackTrace();
		}
	}// end handle location popup
	
	@Override
	public void onBackPressed(){
//do nothing , dont allow
	}

}
